import { login, logout, getUserRouters, getUserInfo, getUserRole } from '@/api/common'
import { formatRouterTree } from '@/utils/loadRoutes'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { Notification } from 'element-ui'

//引入Vue核心库
import Vue from 'vue'
//引入Vuex
import Vuex from 'vuex'
// import { reject, resolve } from 'core-js/fn/promise'
// import { reject } from 'core-js/fn/promise'
//应用Vuex插件
Vue.use(Vuex)

const user = {
    //准备state对象——保存具体的数据
    state: {
        // 用于记录登录状态   登录后直接获取到后端接口传递过来的token，站内页面刷新后的token来自localstorage
        token: getToken(),
        auth: false,
        /**
         * role: 用户角色，根绝它生成动态路由表
         * uid: 用户唯一标识
         */
        user: {},
        role: {},
        // 当前用户的路由表
        routes: [],
        // 后端返回的token
        // token: ''
        // 第一次加载菜单时用到（是否要拉取动态路由）
        loadMenus: false
    },

    //准备mutations对象——修改state中的数据
    mutations: {
        SET_TOKEN: (state, token) => {
            state.token = token
        },
        // 装载用户信息和路由数据
        SET_USER: (state, user) => {
            state.user = user;
        },
        // 装载管理员角色
        SET_ROLE: (state, role) => {
            state.role = role;
        },
        SET_ROUTES: (state, routes) => {
            state.routes = routes;
        },
        SET_AUTH: (state, auth) => {
            state.auth = auth
        },
        SET_LOAD_MENUS: (state, loadMenus) => {
            state.loadMenus = loadMenus
        }
    },

    //准备actions对象——响应组件中用户的动作
    actions: {
        // 用户登录
        login({ commit }, loginForm) {
            // 返回一个promise对象
            return new Promise((resolve, reject) => {
                // 请求封装好的api方法
                login(loginForm.account, loginForm.password).then((res) => {
                    console.log('=========', res);
                    setToken(res.data.token);
                    commit('SET_TOKEN', res.data.token);
                    commit('SET_USER', res.data.userInfoVo);
                    // 第一次加载菜单时用到， 具体见 src 目录下的 permission.js（登录了，表示需要拉取动态路由）
                    commit('SET_LOAD_MENUS', true)
                    resolve();
                }).catch((error) => {
                    reject(error);
                });
            })
        },

        // 获取用户信息
        getUserInfo({ commit }) {
            return new Promise((resolve, reject) => {
                getUserInfo().then(res => {
                    commit('SET_USER', res.data);
                    resolve();
                }).catch(() => {
                    Notification.error({
                        title: "拉取管理员信息失败！",
                        duration: 5000
                    });
                    reject();
                })
            })
        },

        getUserRole({ commit }) {
            return new Promise((resolve, reject) => {
                getUserRole().then(res => {
                    console.log('+++++++++++++++', res.data);
                    commit('SET_ROLE', res.data);
                    resolve();
                }).catch(() => {
                    Notification.error({
                        title: '拉取管理员角色失败！',
                        duration: 5000
                    });
                    reject();
                })
            })
        },
        // 登出
        logout({ commit }) {
            return new Promise((resolve, reject) => {
                logout().then(() => {
                    // 删除vuex记录用户状态的信息
                    commit('SET_TOKEN', '')
                    commit('SET_ROLES', [])
                    removeToken()
                    resolve()
                }).catch(error => {
                    commit('SET_TOKEN', '')
                    commit('SET_ROLES', [])
                    removeToken()
                    reject(error)
                })
            })
        },

        // 加载动态路由
        async setUserRoutes({ commit }) {
            /* // 请求该权限角色的路由数据
            const userRouters = await getUserRouters();
            console.log(userRouters);
            // 将树形结构路由数据进行格式化
            console.log(userRouters.data, '!!!!!!!!!!!!!!!!!!!!!!!!!!!!');
            console.log(typeof Object.values(userRouters.data));
            const routes = formatRouterTree(userRouters.data);
            console.log('路由放vuex里=======', routes);
            // 提交路由信息
            commit('SET_ROUTES', routes);
            console.log(state.routes); */

            return new Promise((resolve, reject) => {
                getUserRouters().then(res => {
                    const data = res.data.map(s => {
                        return {
                            ...s,
                            hidden: s.hidden == "1" ? true : false
                        }
                    })
                    const routes = formatRouterTree(data);
                    console.log("格式化的路由表=======", routes);
                    commit('SET_ROUTES', routes);
                    resolve();
                }).catch(() => {
                    Notification.error({
                        title: '拉取动态路由表失败！',
                        duration: 5000
                    });
                    reject();
                })
            })
        },

        updateLoadMenus({ commit }) {
            commit('SET_LOAD_MENUS', false);
        }
    }
}

//创建并暴露store
export default user